#ifndef __UTIL_HPP
#define __UTIL_HPP

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "logger.hpp"
#include <mysql/mysql.h>
#include <memory>
#include <sstream>
#include "jsoncpp/json/json.h"

#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

//mysql的封装
class mysql_util
{
public:
    //mysql的句柄创建
    static MYSQL *mysql_create(const std::string &host,
        const std::string &username,
        const std::string &password,
        const std::string &dbname,
        uint16_t port = 3306
    )
    {
        MYSQL* mysql = mysql_init(nullptr);
        if(mysql == nullptr)
        {
            ELOG("mysql init failed!!!");
            return nullptr;
        }

        DLOG("mysql 初始化成功");

        //连接服务器
        if(mysql_real_connect(mysql,host.c_str(),username.c_str(),password.c_str(),dbname.c_str(),port,nullptr,0) == nullptr)
        {
            ELOG("connetct mysql server failed: %d",mysql_errno(mysql));
            mysql_close(mysql);
            return nullptr;
        }

        DLOG("mysql 连接服务器成功");

        //设置客户端字符集
        if(mysql_set_character_set(mysql,"utf8") != 0)
        {
            ELOG("set client haracter failed: %d",mysql_errno(mysql));
            mysql_close(mysql);
            return nullptr;
        }

        DLOG("mysql 设置客户端字符集成功");

        return mysql;
    }

    static bool mysql_exec(MYSQL* mysql,const std::string &sql)//执行mysql语句
    {
        int ret = mysql_query(mysql,sql.c_str());
        if(ret != 0)
        {
            ELOG("%s",sql.c_str());
            ELOG("mysql query faild: %s\n",mysql_error(mysql));
            //mysql_close(mysql);
            return false;
        }

        DLOG("mysql 执行语句成功");
        return true;
    }

    static void mysql_destroy(MYSQL* mysql)//mysql的销毁
    {
        if(mysql)
        {
            mysql_close(mysql);
            DLOG("mysql 关闭成功");
        }
    }
};



//json序列化和反序列化封装
class json_util
{
public:
    static bool serialize(const Json::Value &root, std::string& str)
    {
        Json::StreamWriterBuilder swb;
        std::unique_ptr<Json::StreamWriter>sw(swb.newStreamWriter());
        std::stringstream ss;
        int ret = sw->write(root,&ss);
        if(ret != 0)
        {
            ELOG("json serialize failed!!!");
            return false;
        }
        DLOG("json 序列化成功");
        str = ss.str();
        return true;
    }

    static bool unserialize(const std::string& str,Json::Value& root)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader>cr(crb.newCharReader());
        std::string err;
        bool ret = cr->parse(str.c_str(),str.c_str()+str.size(),&root,&err);
        if(ret == false)
        {
            ELOG("json unserialize:%s",err.c_str());
            return false;
        }
        DLOG("json 反序列化成功");
        return true;
    }
};



//字符串切割的封装
class string_util
{
public:
    /*
    *参数：1.所被查找的字符串，2.要查找的字串，3.vector保存分割好字串
    *功能：根据sep来分割src，结果保存到res里
    *返回：分割出来的字符串个数
    */

    static int split(const std::string& src,
                     const std::string& sep,
                     std::vector<std::string>& res
    )
    {
        size_t pos = 0;
        size_t index = 0;

        while(index < src.size())
        {
            pos = src.find(sep,index);
            if(pos == std::string::npos)
            {
                //没有找到，将后面的字串放进去，跳出循环
                res.push_back(src.substr(index));
                break;
            }

            if(pos == index)
            {
                index = pos + sep.size();
                continue;
            } 

            res.push_back(src.substr(index,pos - index));
            index = pos + sep.size();
        }

        return res.size();
    }
};

//文件读取工具类的封装
class file_util
{
public:
    /*
    *参数：1.所要读取的文件名，2.用来保存读取出来的文件数据
    *功能：读取文件，将读取的结果放到body里
    *返回：
    */
    static bool read(const std::string& filename,std::string& body)
    {
        std::ifstream ifs(filename,std::ios::binary);
        if(ifs.is_open() == false)
        {
            ELOG("%s file open failed!!!",filename.c_str());
            return false;
        }

        DLOG("文件打开成功");
        size_t fsize = 0;
        ifs.seekg(0,std::ios::end);//跳转到文件的末尾
        fsize = ifs.tellg();
        ifs.seekg(0,std::ios::beg);
        body.resize(fsize);

        
        ifs.read(&body[0],fsize);
        if(ifs.good() == false)
        {
            ELOG("read %s file content failed!!!",filename.c_str());
            ifs.close();
            return false;
        }
        
        ifs.close();
        DLOG("读取文件成功");
        return true;
    }

};

#endif

